//
//  KVEmoticonKeyboardView.swift
//  KVEmoticon
//
//  Created by 李康卫 on 16/7/29.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

class KVEmoticonKeyboardView: UIView {
    ///保存buttons
    var buttons = [UIButton]()
    ///表情包数
//    var emotionPakeges: [KVEmoticonPackgeModel]?
    ///重用表识
    let reusedCellID = "reusedCellID"
    ///当前点击的按钮
    var crrentBtn = UIButton()
    ///textView
    weak var textView: UITextView?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.height, height: 216)
        super.init(frame: newFrame)
        self.backgroundColor = UIColor.cyanColor()
        //设置UI
        setupUI()
        //添加底部Bar
        addEmoticonToolBarSubView()
        //注册cell
        self.emoticonCollectionView.registerClass(KVEmoticonCell.self, forCellWithReuseIdentifier: reusedCellID)
        
        //加载模型
//        self.emotionPakeges = KVEmoticonModelManeger.sharedEmoticonManeger.emoticonPackages
//        print(emotionPakeges)
    }
    override func layoutSubviews() {
        
        super.layoutSubviews()
         //设置底部子控件的Views
        setupToolBarSubViewsFrame()
        //设置item大小
        let layout = self.emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: self.emoticonCollectionView.bounds.width, height: self.emoticonCollectionView.bounds.height)
    }
    //设置界面
    private func setupUI() {
        //添加子控件
        self.addSubview(emoticonToolBar)
        self.addSubview(emoticonCollectionView)
        self.addSubview(messageLabel)
        self.addSubview(pageControl)
        
        //但第一页时添加Label
        
        //添加pageView
        //添加约束
        self.emoticonToolBar.translatesAutoresizingMaskIntoConstraints = false
        self.emoticonCollectionView.translatesAutoresizingMaskIntoConstraints = false
        self.pageControl.translatesAutoresizingMaskIntoConstraints = false

        let viewDic = ["tb": emoticonToolBar,"cv": emoticonCollectionView]
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic))

        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic))
        
       //page的约束
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.emoticonToolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
       
       
    }
    //设置page的属性
    private func setupPagecontrol(emoticonPageMOdel: KVEmoticonPackgeModel,indexPath: NSIndexPath) {
        //当第一页时添加lable
        if indexPath.section == 0   {
            recentLabel.hidden = false
            pageControl.hidden = true
//            //添加label最近
            self.addSubview(recentLabel)
            //添加label
            recentLabel.translatesAutoresizingMaskIntoConstraints = false
            addConstraint(NSLayoutConstraint(item: recentLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
            addConstraint(NSLayoutConstraint(item: recentLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: emoticonToolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: -5))
        } else {
            recentLabel.hidden = true
            pageControl.hidden = false
            pageControl.currentPage = indexPath.item
            pageControl.numberOfPages = emoticonPageMOdel.emoticonsOfPage.count
        }
    }

    //添加底部VIew的子控件
    private func addEmoticonToolBarSubView() {
        //循环创建4个按钮
        let btnNameArr = ["最近啊", "默认b", "emojic", "浪小花d",]
        for (index,name) in btnNameArr.enumerate() {
            let button = UIButton()
            button.setTitle(name, forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_normal"), forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_selected"), forState: UIControlState.Disabled)
            //设置Button的属性
            button.tag = index
            //添加点击事件
            button.addTarget(self, action: "buttonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Normal)
            if index==0 {
                button.enabled = false
                self.crrentBtn = button
            }
            self.emoticonToolBar.addSubview(button)
            self.buttons.append(button)
        }
    }
    // MARK: - 点击事件
    @objc private func buttonDidClick(btn: UIButton) {
//        print(btn.tag)
        if self.crrentBtn == btn {
            return
        }
        self.emoticonCollectionView.selectItemAtIndexPath(NSIndexPath(forItem: 0, inSection: btn.tag), animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
      swithBtn(btn)
    }
    private func swithBtn(btn: UIButton) {
        self.crrentBtn.enabled = true
        
        //重新选中
        btn.enabled = false
        //调到对应组
        self.crrentBtn = btn
    }
    
    private func setupToolBarSubViewsFrame() {
        //设置buttons的frame
        let btnW = UIScreen.mainScreen().bounds.size.width / CGFloat(self.buttons.count)
        let btnH = self.emoticonToolBar.bounds.height
        for (index,btn) in self.buttons.enumerate() {
            let btnX = btnW * CGFloat(index)
            btn.frame = CGRect(x: btnX, y: 0, width: btnW, height: btnH)
        }
    }
    // MARK: - 懒加载
    private lazy var emoticonCollectionView: UICollectionView = {
        let emoticonLayout = UICollectionViewFlowLayout()
        let emoticonCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: emoticonLayout)
        emoticonCollectionView.backgroundColor = UIColor.randomColor()
        emoticonCollectionView.dataSource = self
        emoticonCollectionView.delegate = self
        //设置属性
        emoticonCollectionView.bounces = false
        emoticonCollectionView.pagingEnabled = true
        emoticonLayout.scrollDirection  = UICollectionViewScrollDirection.Horizontal
        emoticonLayout.minimumInteritemSpacing = 0
        emoticonLayout.minimumLineSpacing = 0
        
        return emoticonCollectionView
    }()
    //底部bar
    private lazy var emoticonToolBar: UIView = {
        let emotiocnToolBar = UIView()
        emotiocnToolBar.backgroundColor = UIColor.randomColor()
        return emotiocnToolBar
    }()
    private lazy var messageLabel: UILabel = {
       let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
        messageLabel.font = UIFont.systemFontOfSize(25)
        
        return messageLabel
    }()
    //加载pageView
    private lazy var pageControl: UIPageControl = {
        
        let pageControl = UIPageControl()
        pageControl.numberOfPages = 6
    
//        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
//        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        //compose_keyboard_dot_selected
        //用运行时获取数性
        // 获取UIPageControl里面的所有属性列表
//        var outCount: UInt32 = 0
//        let ivars = class_copyIvarList(UIPageControl.self, &outCount)
//        //遍历属性获取属性名
//        for i in 0..<outCount {
//            let ivar = ivars[Int(i)]
//            let name = ivar_getName(ivar)
//            let strNmae = String(CString: name, encoding: NSUTF8StringEncoding)
////            print(strNmae)
////            Optional("_currentPageImage")
////            0x0000000110c80c80
////            Optional("_pageImage")
//        }
        //用KVC赋值
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        return pageControl
    }()
    
    private lazy var recentLabel: UILabel = {
        let recentLabel = UILabel()
        recentLabel.text = "最近使用的表情"
        recentLabel.font = UIFont.systemFontOfSize(20)
        recentLabel.textColor = UIColor.purpleColor()
        recentLabel.sizeToFit()
        return recentLabel
    }()
}

//代理
extension KVEmoticonKeyboardView: UICollectionViewDataSource,UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return KVEmoticonModelManeger.sharedEmoticonManeger.emoticonPackages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let emoticonPageModel = KVEmoticonModelManeger.sharedEmoticonManeger.emoticonPackages[section]
        return emoticonPageModel.emoticonsOfPage.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        //给pageContorl赋值
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reusedCellID, forIndexPath: indexPath) as! KVEmoticonCell
//        cell.backgroundColor = UIColor.randomColor()
        
        let emoticonsPageModel = KVEmoticonModelManeger.sharedEmoticonManeger.emoticonPackages[indexPath.section]
        //  设置pagecontorl的number和当前页
        setupPagecontrol(emoticonsPageModel, indexPath: indexPath)
        
        let emoticonsModel: [KVEmoticonModel] = emoticonsPageModel.emoticonsOfPage[indexPath.item]
        cell.emoticons = emoticonsModel
        messageLabel.text = "第\(indexPath.section)组，\(indexPath.item)"
        
        cell.delegate = self
        return cell
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        //判断包含center点的cell所在的组就是toolbar的下标
        var screenCenter = self.emoticonCollectionView.center
        screenCenter.x += scrollView.contentOffset.x
//        print(scrollView.contentOffset.x)
        //遍历当前显示的cell
        //保存选中的indexpath
        for cell in self.emoticonCollectionView.visibleCells() {
            //看他是否包含参照点如果是就进行联动
            if cell.frame.contains(screenCenter) {
                let indexPath = self.emoticonCollectionView.indexPathForCell(cell)
                let index = indexPath?.section

//                print(index)
                self.swithBtn(self.buttons[index!])
            }
        }
     
    }
}
//button的代理
extension KVEmoticonKeyboardView : KVEmoticonCellDelegate {
    func emoticonCellButtonDidClick(emoticonModel: KVEmoticonModel) {
        
        //扩展textView我只管添加
        textView?.insertEmoticon(emoticonModel)
    }
    
    func emoticonCellDeleteBtnDidClick() {
        //文本框删
        textView?.deleteBackward()
    }
}